//
//  AppDelegate.m
//  Shiyun_Newspaper
//
//  Created by Sylar on 2017/5/24.
//  Copyright © 2017年 ShiYun. All rights reserved.
//

#define WIDTH  [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

#import "AppDelegate.h"
#import "MainViewController.h"
#import "LoginViewController.h"
#import "UMSocial.h"
#import "BPush.h"
#import "SN_WebViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "SplashScreenView.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <Bugly/Bugly.h>

#import "SY_Activity.h"
#import "SY_Activity_Model.h"

@interface AppDelegate ()<UIAlertViewDelegate>
{
    UIView *splashView;//广告页
    NSString *urlStr;//广告页的链接
}

@property (nonatomic, copy) NSString *chinnelid;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    //登录状态的通知监听 在登录状态改变的时候触发
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNOTIFICATION_LOGINCHANGE
                                               object:nil];
    
    //设置导航栏颜色
    /*
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithHexString:@"#3bc144"]];
    [[UINavigationBar appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, [UIFont boldSystemFontOfSize:18.0], NSFontAttributeName, nil]];
     */
    
    //状态栏的设置
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [self.window makeKeyAndVisible];
    
    [self loginStateChange:nil];

    [self checkupVersion];
    
    [self setupBugly];
    
    //设置推送字典
    self.notiDict = launchOptions;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //从服务器验证receipt失败之后，在程序再次启动的时候，使用保存的receipt再次到服务器验证
    if (![fileManager fileExistsAtPath:AppStoreInfoLocalFilePath]) {//如果在改路下不存在文件，说明就没有保存验证失败后的购买凭证，也就是说发送凭证成功。
        [fileManager createDirectoryAtPath:AppStoreInfoLocalFilePath//创建目录
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
        
    }else//存在购买凭证，说明发送凭证失败，再次发起验证
    {
        [self sendFailedIapFiles];
    }
    
    //注册友盟分享
    [UMSocialData setAppKey:@"56eb6b22e0f55a9f9600000c"];
    
    //注册推送
    [self registerNotification:application launchOptions:launchOptions];
    
    [self loadOpenPic];
    
    return YES;
}

- (void)setupBugly {
    
    [Bugly startWithAppId:@"398dff4bf5"];
    
    BuglyConfig *config = [BuglyConfig defaultConfig];
    
#if DEBUG
    config.debugMode = YES;
#endif
    config.reportLogLevel = BuglyLogLevelWarn;
    config.blockMonitorEnable = YES;
    config.blockMonitorTimeout = 1.5;
    config.channel = @"Bugly";
}




/**注册推送*/
- (void)registerNotification:(UIApplication *)application launchOptions:(NSDictionary *)launchOptions {
    
    // iOS10 下需要使用新的 API
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
        
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge)
                              completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                  // Enable or disable features based on authorization.
                                  if (granted) {
                                      [application registerForRemoteNotifications];
                                  }
                              }];
#endif
    }
    else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
    
    
#if DEBUG
    [BPush registerChannel:launchOptions apiKey:@"0E2niuvMu5IKiy9vdK5zL1dm" pushMode:BPushModeDevelopment withFirstAction:@"打开" withSecondAction:@"关闭" withCategory:@"test" useBehaviorTextInput:YES isDebug:YES];
#else
    [BPush registerChannel:launchOptions apiKey:@"0E2niuvMu5IKiy9vdK5zL1dm" pushMode:BPushModeProduction withFirstAction:@"打开" withSecondAction:@"关闭" withCategory:@"test" useBehaviorTextInput:YES isDebug:YES];
#endif
    
    
    [BPush disableLbs];
    
    // App 是用户点击推送消息启动
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        [BPush handleNotification:userInfo];
    }

    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    
    [application registerForRemoteNotifications];
    
    
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"test:%@",deviceToken);
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        
        // 需要在绑定成功后进行 settag listtag deletetag unbind 操作否则会失败
        
        // 网络错误
        if (error) {
            return ;
        }
        if (result) {
            // 确认绑定成功
            if ([result[@"error_code"]intValue]!=0) {
                return;
            }
            // 获取channel_id
            NSString *myChannel_id = [BPush getChannelId];
            _chinnelid = myChannel_id;
            NSLog(@"==%@",myChannel_id);
            
            if (USERID) { //绑定
                
                [self bindChinnelId];
                
            }
        }
    }];
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    if (application.applicationState == UIApplicationStateInactive) {
        NSLog(@"通知栏进入");
        
        if (TOKEN) {
            NSString *infoidStr = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"infoid"]];
            NSInteger moveto = [[userInfo objectForKey:@"moveto"] integerValue];
            
            SY_Activity_Model *model = [[SY_Activity_Model alloc] init];
            model.infoid = infoidStr;
            model.moveto = moveto;
            model.url = [userInfo objectForKey:@"url"];
            
            model.apptype = 2;
            [SY_Activity shareActivity].instructionArr = @[model];
            [[SY_Activity shareActivity] action];
        }
        
        
    }else if (application.applicationState == UIApplicationStateActive) {
        NSLog(@"使用中");
    }else if (application.applicationState == UIApplicationStateBackground) {
        NSLog(@"后台");
    }
    
    
}

//绑定chinelid
- (void)bindChinnelId {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setObject:@"api_user_push" forKey:@"method"];
    [param setObject:USERID forKey:@"userid"];
    [param setObject:@"0" forKey:@"clienttype"];
    [param setObject:_chinnelid forKey:@"channelid"];
    [param setObject:@"0" forKey:@"ApplicationIM"];
    
    [Utils getWithparameters:param showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];

}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}


- (void)applicationWillResignActive:(UIApplication *)application {
    
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    [self checkupVersion];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
    
}

//登陆状态改变
-(void)loginStateChange:(NSNotification *)notification {

    if (TOKEN) {//登陆成功加载主窗口控制器
    
        if (_mainController == nil) {
            _mainController = [[MainViewController alloc] init];
        }
        
        self.window.rootViewController = _mainController;
        [self checkupVip];
        
    }else{//登陆失败加载登陆页面控制器
        
        NSUserDefaults * UD = [NSUserDefaults standardUserDefaults];
        [UD setObject:@"0" forKey:@"isLogin"];
        [UD synchronize];
        
        _mainController = nil;
        
        LoginViewController *loginController = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginController];
        
        self.window.rootViewController = nav;
    }
    
    /*
    NSUserDefaults * UD = [NSUserDefaults standardUserDefaults];
    if (![[UD objectForKey:@"firstTime"] isEqualToString:@"1"]) {
        [UD setObject:@"1" forKey:@"firstTime"];
        [UD synchronize];
        UIWindow * window = [[UIApplication sharedApplication].delegate window];
        
        NSArray *imgArr = @[@"unPic",@"wifi_Error",@"unPic"];
        SplashScreenView *spView = [[SplashScreenView alloc] initWithFrame:[[UIScreen mainScreen] bounds] imageDataArr:imgArr];
        [window addSubview:spView];
        
    }
     */
}

- (void)checkupVip {
    
    if (USERID) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        
        [param setObject:@"api_szb_isvip" forKey:@"method"];
        [param setObject:USERID forKey:@"userid"];
        
        [Utils getWithparameters:param showHUD:NO success:^(NSInteger recode, id jsonObject) {
          
            NSDictionary *dict = (NSDictionary *)jsonObject;
            
            NSArray *dataArr = [dict objectForKey:@"re_data"];
            
            NSDictionary *infoDic = [dataArr firstObject];
            
            NSDictionary *imformation = [SyUserInfomation acquirePersonalImformationFromMemoryWithPersonID:USERID];
            NSMutableDictionary *informationM = [NSMutableDictionary dictionaryWithDictionary:imformation];
            
            [informationM setObject:[infoDic objectForKey:@"isvip"] forKey:@"isvip"];
            
            [SyUserInfomation personalImformationSaveWtih:informationM];
            
            
        } failure:^(NSInteger recode, NSError *error) {
            
        }];
    }
    
}
//检测APP版本，是否需要强制升级
- (void)checkupVersion {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setObject:@"api_version" forKey:@"method"];
    
    [Utils getWithparameters:param showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dic = [jsonObject objectForKey:@"re_data"];
        
        if ([dic isKindOfClass:[NSNull class]]) {
            
            return;
        }
        
        if (dic.allValues.count > 0) {
            
            NSString *newVersion = [dic objectForKey:@"version"]; //新版本
            
            NSString *localVersion = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleShortVersionString"];
            
            int versiontype = [[dic objectForKey:@"versiontype"] intValue];
            int type = [[dic objectForKey:@"type"] intValue];
            
            if (type == 1 && versiontype == 1) {
                
                if ([localVersion integerValue] < [newVersion integerValue]) {
                    
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新版本已发布,请更新后使用" delegate:self cancelButtonTitle:nil otherButtonTitles:@"马上更新", nil];
                    
                    alert.tag = 1001;
                    
                    [alert show];
                    
                }
            }
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == 1001){  //更新提示
        
        if (buttonIndex != [alertView cancelButtonIndex]) {
            
            NSString *url = @"https://itunes.apple.com/cn/app/shi-yun/id1246665284?mt=8";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }
    }    
}

//验证receipt失败,App启动后再次验证
- (void)sendFailedIapFiles{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    
    //搜索该目录下的所有文件和目录
    NSArray *cacheFileNameArray = [fileManager contentsOfDirectoryAtPath:AppStoreInfoLocalFilePath error:&error];
    
    if (error == nil)
    {
        for (NSString *name in cacheFileNameArray)
        {
            if ([name hasSuffix:@".plist"])//如果有plist后缀的文件，说明就是存储的购买凭证
            {
                NSString *filePath = [NSString stringWithFormat:@"%@/%@", AppStoreInfoLocalFilePath, name];
                [self sendAppStoreRequestBuyPlist:filePath];
                
            }
        }
    }else {
        NSLog(@"AppStoreInfoLocalFilePath error:%@", [error domain]);
    }
}

-(void)sendAppStoreRequestBuyPlist:(NSString *)plistPath
{
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:@"api_szb_iapverify" forKey:@"Method"];
    [params setObject:[dic objectForKey:@"ORDERID_"] forKey:@"ordercode"];
    [params setObject:[dic objectForKey:@"Request_transactionReceipt"] forKey:@"Receipt"];
    
    [Utils getWithparameters:params showHUD:YES success:^(NSInteger recode, id jsonObject) {
        
        if (recode == 0) {
            [self sendAppStoreRequestSucceededWithData];
        }
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
    
}

//验证成功就从plist中移除凭证
-(void)sendAppStoreRequestSucceededWithData
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:AppStoreInfoLocalFilePath])
    {
        [fileManager removeItemAtPath:AppStoreInfoLocalFilePath error:nil];
    }
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    NSLog(@"%@",url);
    
    NSString *urlString = [NSString stringWithFormat:@"%@",url];
    
    NSArray *objArr = [urlString componentsSeparatedByString:@"//"];
    
    NSString *paramStr = [objArr lastObject];
    
    NSArray *paramArr = [paramStr componentsSeparatedByString:@"&"];
    
    NSMutableDictionary *paramDic = [[NSMutableDictionary alloc]init];
    
    for (NSString *par in paramArr) {
        
        NSArray *arr = [par componentsSeparatedByString:@"="];
        [paramDic setObject:[arr lastObject] forKey:[arr firstObject]];
    }
    
    NSLog(@"%@",paramDic);
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:paramDic forKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
    
    self.notiDict = [[NSDictionary alloc]initWithDictionary:dict];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"URL_Schemes_Notiocation" object:nil];
    
    
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等

        return true;
    }
    return result;
}

- (void)loadOpenPic
{
    
    splashView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    
    UIImageView *whiteBackImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    [whiteBackImage setImage:[Utils imageWithColor:[UIColor whiteColor] size:splashView.size]];
    whiteBackImage.userInteractionEnabled = YES;
    [splashView addSubview:whiteBackImage];
    
    UIImageView *logoBackImage = [[UIImageView alloc]init];
    [logoBackImage setImage:[UIImage imageNamed:@"launch_bottom"]];
    logoBackImage.userInteractionEnabled = YES;
    [splashView addSubview:logoBackImage];
    
    if (HEIGHT == 480 || HEIGHT == 568) {
        
        [logoBackImage setFrame:CGRectMake(0, HEIGHT-98, WIDTH, 98)];
        [logoBackImage setImage:[UIImage imageNamed:@"launch_bottom4"]];
        
    }else if(HEIGHT == 812){
        
        [logoBackImage setFrame:CGRectMake(0, HEIGHT-130, WIDTH, 130)];
        [logoBackImage setImage:[UIImage imageNamed:@"launch_bottomX"]];
        
    }
    else{
        float logoheight = 320/98;
        [logoBackImage setHeight:logoheight];
        
        [logoBackImage mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.bottom.equalTo(self->splashView.mas_bottom).offset(0);
            make.left.equalTo(self->splashView.mas_left).offset(0);
            make.right.equalTo(self->splashView.mas_right).offset(0);
            
        }];
    }
    
    UIImageView * splashImageView = [[UIImageView alloc]init];
    splashImageView.frame = CGRectMake(0, 0, WIDTH, 0);
    splashImageView.userInteractionEnabled = YES;
    
    if (HEIGHT == 736) {
        [splashImageView setHeight:608.33];
    }else if (HEIGHT == 667){
        [splashImageView setHeight:551];
    }else if (HEIGHT == 562){
        [splashImageView setHeight:470];
    }else if (HEIGHT == 480){
        [splashImageView setHeight:383];
    }else if (HEIGHT == 812){
        [splashImageView setHeight:680];
    }
    [splashView addSubview:splashImageView];
    
    [self.window.rootViewController.view addSubview:splashView];
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_startpic_list" forKey:@"method"];
    [dict setObject:@"5" forKey:@"type"];
    [dict setObject:@"0" forKey:@"phonetype"];
    
    if (USERID) {
        
        [dict setObject:USERID forKey:@"userid"];
    }
    
    int width = WIDTH;
    int height = HEIGHT;
    
    [dict setObject:[NSString stringWithFormat:@"%d",width] forKey:@"width"];
    [dict setObject:[NSString stringWithFormat:@"%d",height] forKey:@"height"];
    [Utils getWithparameters:dict showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        NSArray  *arr =[jsonObject objectForKey:@"re_data"];
        
        if ([arr isKindOfClass:[NSArray class]] &&arr.count>0) {
            
            NSDictionary *dic =[arr objectAtIndex:0];
            
            NSString *logo =[dic objectForKey:@"pic"];
            
            self->urlStr = [dic objectForKey:@"url"];
            
            if (logo !=nil ) {
                
                logo =[NSString stringWithFormat:@"%@%@",IMAGEHOSTURL,logo];
                [splashImageView sd_setImageWithURL:[NSURL URLWithString:logo]];
                
                //暂时先不加跳转
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
                [tap addTarget:self action:@selector(pushWebView)];
                [self->splashView addGestureRecognizer:tap];
                
            }else {
                if (HEIGHT == 736) {
                    [splashImageView setImage:[UIImage imageNamed:@"ios_start_6p"]];
                }else if (HEIGHT == 667){
                    [splashImageView setImage:[UIImage imageNamed:@"ios_start_6"]];
                }else if (HEIGHT == 568){
                    [splashImageView setImage:[UIImage imageNamed:@"ios_start_5"]];
                }else if (HEIGHT == 480){
                    [splashImageView setImage:[UIImage imageNamed:@"ios_start_5"]];
                }else if (HEIGHT == 812){
                    [splashImageView setImage:[UIImage imageNamed:@"ios_start_X"]];
                }
            }

        }else {
            
            if (HEIGHT == 736) {
                [splashImageView setImage:[UIImage imageNamed:@"ios_start_6p"]];
            }else if (HEIGHT == 667){
                [splashImageView setImage:[UIImage imageNamed:@"ios_start_6"]];
            }else if (HEIGHT == 568){
                [splashImageView setImage:[UIImage imageNamed:@"ios_start_5"]];
            }else if (HEIGHT == 480){
                [splashImageView setImage:[UIImage imageNamed:@"ios_start_5"]];
            }else if (HEIGHT == 812){
                [splashImageView setImage:[UIImage imageNamed:@"ios_start_X"]];
            }
            
        }
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
        if (HEIGHT == 736) {
            [splashImageView setImage:[UIImage imageNamed:@"ios_start_6p"]];
        }else if (HEIGHT == 667){
            [splashImageView setImage:[UIImage imageNamed:@"ios_start_6"]];
        }else if (HEIGHT == 568){
            [splashImageView setImage:[UIImage imageNamed:@"ios_start_5"]];
        }else if (HEIGHT == 480){
            [splashImageView setImage:[UIImage imageNamed:@"ios_start_5"]];
        }else if (HEIGHT == 812){
            [splashImageView setImage:[UIImage imageNamed:@"ios_start_X"]];
        }
        
    }];
    
    [self performSelector:@selector(hideAdView) withObject:nil afterDelay:3.0];
}


- (void)pushWebView {
    
    [self hideAdView];
    
    if (urlStr.length > 0) {
        SN_WebViewController *web = [[SN_WebViewController alloc] init];
        web.url = urlStr;
        
        [[Utils getCurrentVC].navigationController pushViewController:web animated:YES];
    }
    
}
 

- (void)hideAdView {
    
    if (splashView) {
        [splashView removeFromSuperview];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"advimageDisapper" object:nil];
    }
    
}



@end
